<template>
  <div>
    <el-backtop target=".app-main"></el-backtop>
    <el-row :gutter="20" style="margin: 10px 0;">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="card-header">
            <span style="font-size: 120%;">{{$route.meta.title}}列表</span>
            <vxe-input v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @input="searchEvent"></vxe-input>
          </div>
          <div class="">
            <vxe-table resizable ref="XDefaultTable" show-overflow border height="528" stripe highlight-hover-row
                       highlight-current-row resizable :loading="loading" :data="dataBodyList" @sort-change="sortChange">
              <vxe-column field="schoolTerm" title="学期" sortable>
              </vxe-column>
              <vxe-column field="resultType" title="考试类型" sortable></vxe-column>
              <vxe-column field="player" title="运动员" sortable></vxe-column>
              <vxe-column field="subject" title="科目" sortable></vxe-column>
              <vxe-column field="" title="操作" width="60">
                <template #default="{ row, rowIndex}">
                  <el-button @click="previewEvent(row)" type="primary" size="small" circle icon="el-icon-view">
                  </el-button>
                </template>
              </vxe-column>
            </vxe-table>
            <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize"
                       :total="page.totalResult" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                       @page-change="handlePageChange">
            </vxe-pager>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span style="font-size: 120%;">{{$route.meta.title}}查询</span>
          </div>
          <div class="card-body">
            <el-form class="cultureScoreForm" inline-message ref="cultureScoreForm" :model="cultureScoreForm"
                     :rules="rules" label-width="110px">
              <el-form-item label="学期">
                <span class="schoolTermName">{{this.dict_school_term[cultureScoreForm.schoolTermId]}}</span><br>
                <el-button-group>
                  <el-button @click="cultureScoreForm.schoolTermId-=1" size="small">上一学期</el-button>
                  <el-button @click="cultureScoreForm.schoolTermId+=1" size="small">下一学期</el-button>
                  <el-button @click="cultureScoreForm.schoolTermId=currentSchoolTermId" size="small">回到当前学期</el-button>
                </el-button-group>
              </el-form-item>
              <el-form-item label="考试类型" prop="resultTypeId">
                <el-radio-group v-model="cultureScoreForm.resultTypeId" size="small">
                  <el-radio-button label="2">期中</el-radio-button>
                  <el-radio-button label="3">期末</el-radio-button>
                  <el-radio-button label="1">平时</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="运动项目">
                <el-select v-model="cultureScoreForm.sportId" @change="sportChange" filterable clearable
                           style="width: 100%;" placeholder="请选择">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="运动小项">
                <el-select v-model="cultureScoreForm.sportItemId" @change="sportItemChange" filterable clearable
                           style="width: 100%;" placeholder="请选择">
                  <el-option :label="item.name" :value="item.sportItemId" v-for="(item,index) in sportItemData"
                             :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="运动员" prop="playerIdStr">
                <el-select v-model="cultureScoreForm.playerIdStr" multiple filterable clearable collapse-tags
                           placeholder="请选择">
                  <el-option :label="item.name" :value="item.playerId" v-for="(item,index) in playerData" :key="index">
                  </el-option>
                </el-select>
                <el-button type="primary" @click='playerSelectAll'>全选</el-button>
              </el-form-item>
              <el-form-item label="科目" prop="subjectIdStr">
                <el-select v-model="cultureScoreForm.subjectIdStr" multiple filterable clearable collapse-tags
                           placeholder="请选择">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in dict_subject" :key="index">
                  </el-option>
                </el-select>
                <el-button type="primary" @click="cultureScoreForm.subjectIdStr = Object.keys(dict_subject)">全选
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button @click="go" :disabled="tableColumn.length!=0" size="small" type="primary"
                           icon="el-icon-s-tools">
                  查看</el-button>
                <el-button @click="tableColumn=[];dataList=[];" size="small" type="warning">清空</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-card class="box-card" style="height:800px;" >
      <div class="table">
        <vxe-toolbar>
          <template #buttons>
            <el-button type="success" icon="el-icon-download" size="small" @click="exportDataAll">导出</el-button>
            <el-button type="success" icon="el-icon-printer" size="small" @click="printEventAll">打印</el-button>
          </template>
        </vxe-toolbar>

        <vxe-table resizable ref="XTable" show-overflow border max-height="700"  stripe highlight-hover-row
                   highlight-current-row highlight-current-column :loading="loading" :data="dataList">
          <vxe-table-column v-for="(item,index) in tableColumn" :key="index" :type="item.type" :field="item.field"
                            :title="item.title" :fixed="item.fixed" :min-width="item.width" align="center" :filters="item.filters">
            <template v-if="!item.field" #default="{ row }">
              <el-button @click="save(row)" type="primary" size="mini" icon="iconfont icon-save" circle></el-button>
            </template>
            <template v-else-if="item.mode=='input'" #default="{ row }">
              <span v-if="row[item.field]">{{row[item.field]}}</span>
              <span v-else>-</span>
            </template>
          </vxe-table-column>
        </vxe-table>

      </div>
    </el-card>
  </div>
</template>

<script>
  import {
    currentRolePlayer,
    currentTerm,
    sport_item_by_sportId,
    get_player,
    orgSubject,
    result4coach,
    edu_examination_results,
    defaultCultureResultReport4coach
  } from "@/api/person.js"
  import {
    sport_by_org,
    sport_item,
  } from "@/api/dict.js"


  export default {

    data() {
      return {
        dict_school_term: this.$store.state.user.dict_school_term,
        dict_sport: {},
        dict_sportItem: {},
        dict_player: {},
        dict_subject: {},
        dict_resultType: this.$store.state.user.dict_cultureResultType,
        cultureScoreForm: {
          schoolTermId: '',
          resultTypeId: '',
          sportId: '',
          sportItemId: '',
          playerIdStr: '',
          subjectIdStr: '',
        },
        sportItemData: [],
        playerData: [],
        currentSchoolTermId: '',
        rules: {
          resultTypeId: [{
            required: true,
            message: '请选择考试类型',
            trigger: 'change'
          }, ],
          playerIdStr: [{
            required: false,
            message: '请选择运动员',
            trigger: 'change'
          }, ],
          subjectIdStr: [{
            required: false,
            message: '请选择科目',
            trigger: 'change'
          }, ],
        },
        loading: false,
        dataList: [],
        tableColumn: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        dataBodyList: [],
        dataBodyListSource: [],
        dataHeader: [],
        filterName: '',
        sVal: '',
      }
    },
    created() {
      this.getCurrentTerm()
    },
    methods: {
      previewEvent(row) {
        this.cultureScoreForm = row
        let data = {};
        this.tableColumn = [];
        data.playerIds = row.playerIds
        data.playerIdStr = row.playerIds
        data.subjectIdStr = row.subjectIds
        data.subjectIds = row.subjectIds
        data.schoolTermId = row.schoolTermId
        data.resultTypeId = row.resultTypeId
        result4coach(data).then(res => {
          if (res.code === 200 && res.data.length!=0) {
            let tableData = []
            data.playerIds.split(",").forEach(item => {
              let obj = {}
              obj['playerName'] = this.dict_player[parseInt(item)]
              obj['playerId'] = item
              data.subjectIds.split(',').forEach((item2, index2) => {
                this.tableColumn.push({
                  key: index2 + 1,
                  field: item2,
                  width: 100,
                  mode: 'input',
                  title: this.dict_subject[item2]
                })
                obj[item2] = ''
              })
              tableData.push(obj)
            })
            if (res.data.length != 0) {
              res.data.forEach(item => {
                tableData.forEach(item2 => {
                  if (item.playerId == item2.playerId) {
                    item2[item.subjectId] = item.score
                  }
                })
              })
              //    console.log(tableData)

              //   let tableData222 = {}
              //   let defaultObj = {}
              //   data.subjectIdStr.split(',').forEach((item)=>defaultObj[item] = "")
              //    res.data.forEach((item)=>{
              //      let currentObj = tableData222[item.playerId]
              //      if(!currentObj){
              //         tableData222[item.playerId] = {...defaultObj}
              //        tableData222[item.playerId].playerId = item.playerId
              //        tableData222[item.playerId].playerName = this.dict_player[item.playerId]

              //      }
              //      tableData222[item.playerId][item.subjectId] = item.score
              //    })
              // }
              // let tableDataArr =  Object.values(tableData222);
              this.dataList = tableData
              this.tableColumn = this.deWeightThree(this.tableColumn)
              this.tableColumn.unshift({
                field: 'playerName',
                title: '姓名',
                fixed: 'left',
                width: 80,
              })
            } else {
              this.$message.error(res.message)
            }
          }
        })
      },



      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
      },
      exportDataAll() {
        this.$refs.XTable.exportData({
          filename: this.dict_school_term[this.cultureScoreForm.schoolTermId],
          data: this.dataList
        })
      },
      printEventAll() {
        let topHtml = '<h2>' + this.dict_school_term[this.cultureScoreForm.schoolTermId] + '</h2>'
        this.$refs.XTable.print({
          sheetName: this.dict_school_term[this.cultureScoreForm.schoolTermId],
          beforePrintMethod: ({
            content
          }) => {
            return topHtml + content
          }
        })
      },

      save(row) {
        let data = []
        this.cultureScoreForm.subjectIdStr.forEach(item => {
          if (row[item]) {
            data.push({
              playerId: row.playerId,
              resultTypeId: this.cultureScoreForm.resultTypeId,
              schoolTermId: this.cultureScoreForm.schoolTermId,
              score: row[item],
              studentId: -1,
              subjectId: item,
            })
          }
        })
        edu_examination_results(data).then(res => {
          if (res.code === 200) {
            this.$message.success('保存成功！')
          }
        })
      },
      go() {
        this.rules.playerIdStr[0].required = true
        this.rules.subjectIdStr[0].required = true
        this.$refs.cultureScoreForm.validate((valid) => {
          if (valid) {
            let data = {}
            if (this.cultureScoreForm.schoolTermId) data.schoolTermId = this.cultureScoreForm.schoolTermId
            if (this.cultureScoreForm.resultTypeId) data.resultTypeId = this.cultureScoreForm.resultTypeId
            if (this.cultureScoreForm.playerIdStr) data.playerIdStr = this.cultureScoreForm.playerIdStr.join(',')
            if (this.cultureScoreForm.subjectIdStr) data.subjectIdStr = this.cultureScoreForm.subjectIdStr.join(',')
            this.loading = true
            result4coach(data).then(res => {
              if (res.code === 200) {
                let tableData = []
                this.cultureScoreForm.playerIdStr.forEach(item => {
                  let obj = {}
                  obj['playerName'] = this.dict_player[item]
                  obj['playerId'] = item
                  this.cultureScoreForm.subjectIdStr.forEach((item2, index2) => {
                    this.tableColumn.push({
                      key: index2 + 1,
                      field: item2,
                      width: 100,
                      mode: 'input',
                      title: this.dict_subject[item2]
                    })
                    obj[item2] = ''
                  })
                  tableData.push(obj)
                })
                if (res.data.length != 0) {
                  res.data.forEach(item => {
                    tableData.forEach(item2 => {
                      if (item.playerId == item2.playerId) {
                        item2[item.subjectId] = item.score
                      }
                    })
                  })
                }
                this.dataList = tableData
                this.tableColumn = this.deWeightThree(this.tableColumn)
                this.tableColumn.unshift({
                  field: 'playerName',
                  title: '姓名',
                  fixed: 'left',
                  width: 80,
                })
                this.loading = false
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            return false;
          }
        })
      },
      deWeightThree(arr) {
        var temp = [];
        arr.forEach(function(a) {
          var check = temp.every(function(b) {
            return a.key !== b.key;
          })
          check ? temp.push(a) : ''
        })
        return temp;
      },
      playerSelectAll() {
        this.cultureScoreForm.playerIdStr = []
        this.playerData.forEach(item => {
          this.cultureScoreForm.playerIdStr.push(item.playerId)
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = ['player','resultType','schoolTerm','subject']
          const rest = this.dataBodyListSource.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataBodyList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
            currentPage: 1,
            pageSize: this.dataBodyList.length,
            totalResult: this.dataBodyList.length
          }
          this.search = true
        } else {
          this.dataBodyList = this.dataBodyListSource
        }
      },
      sportChange() {
        this.cultureScoreForm.sportItemId = ''
        this.cultureScoreForm.playerIdStr = ''
        sport_item_by_sportId({
          sportId: this.cultureScoreForm.sportId
        }).then(res => {
          if (res.code === 200) {
            this.sportItemData = res.data
            this.get_player()
          }
        })
      },
      sportItemChange() {
        this.cultureScoreForm.playerIdStr = ''
        this.get_player()
      },
      async get_player() {
        let data = {}
        if (this.cultureScoreForm.sportId) data.sportId = this.cultureScoreForm.sportId
        if (this.cultureScoreForm.sportItemId) data.sportItemId = this.cultureScoreForm.sportItemId
        let res = await get_player(data)
        this.playerData = res.data
        res.data.forEach(item => {
          this.dict_player[item.playerId] = item.name
        })
      },

      getCurrentTerm() {
        this.init_dict().then(() => {
          currentTerm().then(res => {
            if (res.code === 200) {
              this.currentSchoolTermId = res.data.schoolTermId
              this.cultureScoreForm.schoolTermId = res.data.schoolTermId
            }
          })
        }).then(() => this.get_player()).then(() =>currentRolePlayer())
          .then(() => this.init_defaultCultureResultReport4coach())
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          sport_by_org().then(res => {
            this.dict_sport = res
          })
          sport_item().then(res => {
            this.dict_sportItem = res
          })
          orgSubject().then(res => {
            res.data.forEach(item => {
              this.dict_subject[item.subjectId] = item.alias
            })
          })
          resolve()
        })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item=>{
          if(item.playerIds){
            let arr = item.playerIds.split(',')
            let playerArr = []
            arr.forEach(player=>{
              playerArr.push(this.dict_player[player])
            })
            item.player = playerArr.join(',')
          }
          if(item.subjectIds){
            let arr = item.subjectIds.split(',')
            let subjectArr = []
            arr.forEach(subject=>{
              subjectArr.push(this.dict_subject[subject])
            })
            item.subject = subjectArr.join(',')
          }
          item.schoolTerm = this.dict_school_term[item.schoolTermId]
          item.resultType = this.dict_resultType[item.resultTypeId]
        })
        this.dataBodyListSource = data
      },
      async init_defaultCultureResultReport4coach() {
        let res = await defaultCultureResultReport4coach()
        if(res.code === 200 && res.data.lengt!=0) {
          this.init_data(res.data)
        }else{
          this.dataBodyListSource = []
        }
        this.findList()
      },
      findList() {
        setTimeout(() => {
            this.page.totalResult = this.dataBodyListSource.length
            this.dataBodyList = this.dataBodyListSource.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.loading = false
        }, 300)
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.dataBodyListSource.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataBodyList.length
      	}
      },
    },
  }
</script>

<style lang="scss" scoped>
  .cultureScore {
    width: 50%;
    background-color: #FFFFFF;
    padding: 20px 0 20px 20%;
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;

    .cultureScoreForm {
      width: 500px;

      .schoolTermName {
        font-size: 120%;
        font-weight: bold;
      }
    }
  }

  .table {
    width: 100%;
    padding: 10px;
  }

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .card-body {
    height: 590px;
  }
</style>
